<?php

namespace app\queue\task;

use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use support\Db;
use ZipArchive;

class QiniuFileProcessTask
{
    // 处理队列任务的方法
    public function handle()
    {
        // 1. 查询数据库获取七牛云CDN链接地址
        $cdnUrls = $this->queryCdnUrlsFromDb();

        // 2. 下载七牛云的文件到本地并打包压缩
        $zipFileName = $this->downloadAndZipFiles($cdnUrls);

        // 3. 上传到七牛云并获取新的下载链接地址
        $newDownloadUrl = $this->uploadToQiniu($zipFileName);

        // 这里可以根据需求进一步处理返回的下载链接地址，比如保存到数据库等
        return $newDownloadUrl;
    }

    private function queryCdnUrlsFromDb()
    {
        return Db::table('your_table_name')
            ->select('qiniu_cdn_url')
            ->get()
            ->pluck('qiniu_cdn_url')
            ->toArray();
    }

    private function downloadAndZipFiles($cdnUrls)
    {
        $accessKey = 'YOUR_ACCESS_KEY';
        $secretKey = 'YOUR_SECRET_KEY';
        $bucket = 'YOUR_BUCKET_NAME';

        $auth = new Auth($accessKey, $secretKey);
        $bucketManager = new BucketManager($auth);

        $zipFileName = 'downloaded_files.zip';
        $zip = new ZipArchive();
        if ($zip->open($zipFileName, ZipArchive::CREATE) === true) {
            foreach ($cdnUrls as $cdnUrl) {
                // 解析出文件名等信息（根据七牛云CDN URL格式解析）
                $fileName = basename(parse_url($cdnUrl, PHP_URL_PATH));
                // 从七牛云下载文件到本地临时路径
                list($ret, $err) = $bucketManager->fetch($cdnUrl, $bucket, $fileName);
                if ($err !== null) {
                    // 处理下载出错情况
                    continue;
                }
                // 将下载的文件添加到压缩包
                $zip->addFile($fileName, $fileName);
            }
            $zip->close();
        }

        return $zipFileName;
    }

    private function uploadToQiniu($zipFileName)
    {
        $accessKey = 'YOUR_ACCESS_KEY';
        $secretKey = 'YOUR_SECRET_KEY';
        $bucket = 'YOUR_BUCKET_NAME';
        $key = basename($zipFileName);

        $auth = new Auth($accessKey, $secretKey);
        $token = $auth->uploadToken($bucket);

        $uploadMgr = new UploadManager();
        list($ret, $err) = $uploadMgr->putFile($token, $key, $zipFileName);
        if ($err !== null) {
            // 处理上传出错情况
            return false;
        }
        // 构建新的七牛云下载链接地址
        $domain = 'YOUR_QINIU_DOMAIN';
        $newDownloadUrl = "https://{$domain}/{$key}";
        return $newDownloadUrl;
    }
}
